package tdh.xt.dao.hibernate;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import tdh.xt.conditional.HibernateCondition;
import tdh.xt.dao.UserDao;
import tdh.xt.entity.po.User;
import tdh.xt.entity.vo.Page;

import java.util.List;
import java.util.Map;

/*
* @Package tdh.xt.dao.hibernate
* @Description Hibernate用户Dao
* @Author RicarAN
* @Date 2021/6/15 16:19
* @Copyright (c) 2021,南京通达海科技股份有限公司 All Rights Reserved.
* @Version 1.0
* Modification History:
* Date                  Author      Version     Description
* ------------------------------------------------------------------
* 2021/6/15 16:19       RicarAN      1.0        Hibernate用户Dao
*
*/
@Repository("userDao")
@Conditional(HibernateCondition.class)
public class UserDaoImpl implements UserDao {

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Autowired
    SessionFactory sessionFactory;

    /*
     * @description 根据用户id查询用户
     * @param yhid 用户id
     * @return tdh.xt.entity.po.User 查询到的用户，未查询到返回null
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:20
     */
    @Override
    public User getUserByYhid(String yhid) {
        Session session = sessionFactory.getCurrentSession();
        List list = session
                .createQuery("from User where yhid=:yhid")
                .setParameter("yhid", yhid)
                .list();
        for (Object o : list) {
            session.evict(o);
        }
        return list.isEmpty() ? null : (User) list.get(0);
//        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
//        criteria.add(Restrictions.eq("yhid", yhid));
//        List<User> list = (List<User>) hibernateTemplate.findByCriteria(criteria);
//        return list.isEmpty() ? null : list.get(0);
    }

    /*
     * @description 根据用户id或用户姓名查找用户，用户姓名采用模糊查询
     * @param yhidOrYhxm 用户id或用户姓名
	 * @param page       分页信息
     * @return java.util.List<tdh.xt.entity.po.User> 分页后的用户列表数据
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:21
     */
    @Override
    public List<User> getUsersByYhidOrYhxm(String yhidOrYhxm, Page page) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from User";
        if (!StringUtils.isEmpty(yhidOrYhxm)) {
            hql += " where yhxm like :yhxm or yhid = :yhid";
        }
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(yhidOrYhxm)) {
            query.setParameter("yhxm", "%" + yhidOrYhxm + "%").setParameter("yhid", yhidOrYhxm);
        }
        List list = query.setFirstResult(page.getOffset()).setMaxResults(page.getLimit()).list();
        for (Object o : list) {
            session.evict(o);
        }
        return list;
//        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
//        if (!StringUtils.isEmpty(yhidOrYhxm)) {
//            criteria.add(Restrictions.or(
//                    Restrictions.like("yhxm", yhidOrYhxm, MatchMode.ANYWHERE),
//                    Restrictions.eq("yhid", yhidOrYhxm)));
//        }
//        return (List<User>) hibernateTemplate.findByCriteria(criteria, page.getOffset(), page.getLimit());
    }

    /*
     * @description 根据用户代码删除用户
     * @param yhdm 用户代码
     * @return int 影响的行数
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:22
     */
    @Override
    public int deleteByYhdm(String yhdm) {
        User user = hibernateTemplate.get(User.class, yhdm);
        if (user == null) {
            return -1;
        }
        hibernateTemplate.delete(user);
        if (hibernateTemplate.get(User.class, yhdm) != null) {
            return 0;
        }
        return 1;
    }

    /*
     * @description 通过部门代码获取用户
     * @param bmdm 部门代码
	 * @param page 分页信息
     * @return java.util.List<tdh.xt.entity.po.User> 分页后的用户列表数据
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:22
     */
    @Override
    public List<User> getUsersByBmdm(String bmdm, Page page) {
        Session session = sessionFactory.getCurrentSession();
        List list = session.createQuery("from User where yhbm=:yhbm")
                .setParameter("yhbm", bmdm)
                .setFirstResult(page.getOffset())
                .setMaxResults(page.getLimit())
                .list();
        for (Object o : list) {
            session.evict(o);
        }
        return list;
//        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
//        criteria.add(Restrictions.eq("yhbm", bmdm));
//        return (List<User>) hibernateTemplate.findByCriteria(criteria, page.getOffset(), page.getLimit());
    }

    /*
     * @description 根据用户代码查找用户
     * @param yhdm 用户代码
     * @return tdh.xt.entity.po.User 用户信息，为空返回null
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:23
     */
    @Override
    public User getUserByYhdm(String yhdm) {
        User user = hibernateTemplate.get(User.class, yhdm);
        if (user != null) {
            sessionFactory.getCurrentSession().evict(user);
        }
        return user;
    }

    /*
     * @description 插入用户
     * @param user 待插入的用户
     * @return int 影响的行数
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:23
     */
    @Override
    public int insert(User user) {
        hibernateTemplate.saveOrUpdate(user);
        return 1;
    }

    /*
     * @description 通过用户代码更新用户
     * @param user 用户
     * @return int 影响的行数
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:24
     */
    @Override
    public int updateByYhdm(User user) {
        return insert(user);
    }

    /*
     * @description 获取所有用户列表分页后的数据
     * @param page 分页信息
     * @return java.util.List<tdh.xt.entity.po.User> 分页好的数据
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:24
     */
    @Override
    public List<User> getUserList(Page page) {
        Session session = sessionFactory.getCurrentSession();
        List list = session
                .createQuery("from User")
                .setFirstResult(page.getOffset())
                .setMaxResults(page.getLimit())
                .list();
        for (Object o : list) {
            session.evict(o);
        }
        return list;
//        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
//        return (List<User>) hibernateTemplate.findByCriteria(criteria, page.getOffset(), page.getLimit());
    }

    /*
     * @description 获得数据库中总条数
     * @param pageSize 分页大小
	 * @param map      查询条件
     * @return int 指定查询条件下的总条数
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:25
     */
    @Override
    public int getTotalPageCount(Integer pageSize, Map<String, Object> map) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        StringBuilder hql = new StringBuilder("select count(*) from User");
        int index = 0;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (index++ == 0) {
                hql.append(" where ");
            }
            String key = entry.getKey();
            if (key.contains("like")) {
                hql.append(" " + entry.getKey() + " CONCAT('%',?,'%') ");
            } else if(key.startsWith("or ")) {
                hql.append(" " + entry.getKey() + " = ?");
            } else {
                if (index++ != 1) {
                    hql.append(" and");
                }
                hql.append(" " + entry.getKey() + " = ?");
            }
        }
        Query query = session.createQuery(hql.toString());
        index=0;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            query.setParameter(index++, entry.getValue());
        }
        return ((Long)(query.iterate().next())).intValue();
    }

}
